import { defineStore } from 'pinia'
import { Client } from '@stomp/stompjs'
import {useAuthStore} from "@/stores/modules/authStore.js";
import { chatAPI } from '@/api/chat/index.js'
import { useStorage } from '@vueuse/core'

export const chatSimpleStore = defineStore('chatSimple', {
    state: () => ({
        connectionStatus: 'disconnected',
        stompClient: null,
        receivedMessages: [],
        // 使用本地存储持久化私聊消息
        privateMessages: useStorage('chat-private-messages', {}),
        currentUser: null,
        lastSentMessageId: null,
        friendList: [],
        friendGroups: {
            online: {
                id: 'online',
                name: '在线好友',
                friends: []
            },
            offline: {
                id: 'offline',
                name: '离线好友',
                friends: []
            }
        },
        loadingFriends: false,
        error: null,
        onlineStatusPolling: {}
    }),
    actions: {
        async fetchFriendList() {
            this.loadingFriends = true;
            this.error = null;

            try {
                const authStore = useAuthStore();
                const userId = authStore.userInfo?.id;
                if (!userId) throw new Error('用户未登录');

                console.log('[fetchFriendList] 开始获取好友列表，用户ID:', userId);
                const friends = await chatAPI.getFormattedFriendList(userId);
                console.log('[fetchFriendList] 获取到好友列表:', friends);

                this.friendList = friends;

                // 更新分组
                this.updateFriendGroups();

                // 为每个好友启动在线状态轮询
                this.startOnlineStatusPolling();

                return friends;
            } catch (err) {
                console.error('[fetchFriendList] 获取好友列表失败:', err);
                this.error = err.message || '获取好友列表失败';
                throw err;
            } finally {
                this.loadingFriends = false;
            }
        },

        // 更新好友分组
        updateFriendGroups() {
            this.friendGroups.online.friends = this.friendList.filter(f => f.online);
            this.friendGroups.offline.friends = this.friendList.filter(f => !f.online);
        },

        // 启动在线状态轮询
        startOnlineStatusPolling() {
            // 先清除所有现有的轮询
            Object.values(this.onlineStatusPolling).forEach(intervalId => {
                clearInterval(intervalId);
            });
            this.onlineStatusPolling = {};

            // 为每个好友启动新的轮询
            this.friendList.forEach(friend => {
                this.pollFriendOnlineStatus(friend.id);
            });
        },

        // 轮询好友在线状态
        async pollFriendOnlineStatus(friendId) {
            // 如果已经有轮询，先清除
            if (this.onlineStatusPolling[friendId]) {
                clearInterval(this.onlineStatusPolling[friendId]);
            }

            // 立即获取一次状态
            await this.updateSingleFriendStatus(friendId);

            // 设置轮询间隔（每30秒检查一次）
            this.onlineStatusPolling[friendId] = setInterval(async () => {
                await this.updateSingleFriendStatus(friendId);
            }, 30000);
        },

        // 更新单个好友的在线状态
        async updateSingleFriendStatus(friendId) {
            try {
                console.log('[updateSingleFriendStatus] 更新好友在线状态，好友ID:', friendId);
                const statusData = await chatAPI.getFriendOnlineStatus(friendId);

                const friend = this.friendList.find(f => f.id === friendId);
                if (friend) {
                    const wasOnline = friend.online;
                    friend.online = statusData.online === 1;
                    friend.lastSeen = statusData.lastActive ? formatLastSeen(statusData.lastActive) : '未知';

                    // 如果在线状态发生变化，更新分组
                    if (wasOnline !== friend.online) {
                        this.updateFriendGroups();
                        // 如果好友从离线变为在线，检查离线消息
                        if (friend.online && !wasOnline) {
                            this.checkOfflineMessages(friendId);
                        }
                    }
                }
            } catch (error) {
                console.error('[updateSingleFriendStatus] 更新好友在线状态失败:', error);
            }
        },

        // 检查离线消息
        async checkOfflineMessages(friendId) {
            try {
                console.log('[checkOfflineMessages] 检查离线消息，好友ID:', friendId);
                // 这里可以添加从服务器获取离线消息的逻辑
                // 实际项目中这里应该调用API获取离线消息
                // 模拟获取离线消息
                const offlineMessages = await this.getOfflineMessagesFromServer(friendId);

                if (offlineMessages && offlineMessages.length > 0) {
                    console.log('[checkOfflineMessages] 收到离线消息:', offlineMessages);

                    // 初始化该好友的消息数组
                    if (!this.privateMessages[friendId]) {
                        this.privateMessages[friendId] = [];
                    }

                    // 添加离线消息到本地存储
                    offlineMessages.forEach(msg => {
                        this.privateMessages[friendId].push({
                            from: msg.from,
                            content: msg.content,
                            timestamp: new Date(msg.timestamp),
                            isSelf: false,
                            messageId: msg.messageId
                        });
                    });

                    // 更新未读计数
                    const friend = this.friendList.find(f => f.id === friendId);
                    if (friend) {
                        friend.unread = (friend.unread || 0) + offlineMessages.length;
                    }
                }
            } catch (error) {
                console.error('[checkOfflineMessages] 检查离线消息失败:', error);
            }
        },

        // 模拟从服务器获取离线消息
        async getOfflineMessagesFromServer(friendId) {
            // 实际项目中这里应该调用API获取离线消息
            // 这里只是模拟返回空数组
            return [];
        },

        // 更新好友状态（用于WebSocket通知）
        updateFriendStatus(friendId, status) {
            console.log('[updateFriendStatus] 通过WebSocket更新好友状态，好友ID:', friendId, '状态:', status);
            const friend = this.friendList.find(f => f.id === friendId);
            if (friend) {
                const wasOnline = friend.online;
                friend.online = status === 1;
                friend.lastSeen = '刚刚';

                // 如果在线状态发生变化，更新分组
                if (wasOnline !== friend.online) {
                    this.updateFriendGroups();
                    // 如果好友从离线变为在线，检查离线消息
                    if (friend.online && !wasOnline) {
                        this.checkOfflineMessages(friendId);
                    }
                }
            }
        },

        connect() {
            console.log('[connect] 开始连接WebSocket');
            const authStore = useAuthStore();
            this.currentUser = authStore.userInfo;
            console.log('[connect] 当前用户信息:', this.currentUser);

            if (this.connectionStatus === 'connected' || this.connectionStatus === 'connecting') {
                console.log('[connect] 已连接或正在连接，跳过');
                return;
            }

            this.connectionStatus = 'connecting';

            this.stompClient = new Client({
                brokerURL: 'ws://localhost:9998/ws',
                connectHeaders:{Authorization : `${authStore.token}`},
                debug: (str) => console.log('[STOMP DEBUG]', str),
                reconnectDelay: 5000,
                heartbeatIncoming: 4000,
                heartbeatOutgoing: 4000,

                onConnect: (frame) => {
                    console.log('[onConnect] 连接成功，frame:', frame);
                    this.connectionStatus = 'connected';
                    this.subscribe();
                    this.subscribePrivateChat();
                    this.subscribeStatusUpdates();
                    this.subscribeOfflineMessages();
                },

                onDisconnect: () => {
                    console.log('[onDisconnect] 连接断开');
                    this.connectionStatus = 'disconnected';
                    this.unsubscribe();
                },

                onStompError: (frame) => {
                    console.error('[onStompError] 连接失败，frame:', frame);
                    this.connectionStatus = 'error';
                }
            });

            console.log('[connect] 激活STOMP客户端');
            this.stompClient.activate();
        },

        // 订阅离线消息频道
        subscribeOfflineMessages() {
            console.log('[subscribeOfflineMessages] 订阅离线消息频道');
            if (this.connectionStatus !== 'connected') return;

            this.stompClient.subscribe('/user/queue/offline', (message) => {
                console.log('[subscribeOfflineMessages] 收到离线消息:', message);
                try {
                    const messageData = JSON.parse(message.body);
                    console.log('[subscribeOfflineMessages] 解析后的离线消息数据:', messageData);

                    const { from, content, timestamp, messageId } = messageData;
                    if (!messageData.from) {
                        console.error('[subscribeOfflineMessages] 错误：消息缺少 from', messageData);
                        return;
                    }

                    // 初始化该好友的消息数组
                    if (!this.privateMessages[from]) {
                        console.log('[subscribeOfflineMessages] 初始化好友消息数组，好友ID:', from);
                        this.privateMessages[from] = [];
                    }

                    const newPrivateMessage = {
                        from,
                        content,
                        timestamp: new Date(timestamp),
                        isSelf: false,
                        messageId
                    };

                    console.log('[subscribeOfflineMessages] 准备添加的离线消息:', newPrivateMessage);
                    this.privateMessages[from].push(newPrivateMessage);
                    console.log('[subscribeOfflineMessages] 更新后的私聊消息列表:', this.privateMessages[from]);

                    // 更新好友未读消息计数
                    const friend = this.friendList.find(f => f.id === from);
                    if (friend) {
                        console.log('[subscribeOfflineMessages] 更新好友未读计数，好友ID:', from, '当前未读:', friend.unread || 0);
                        friend.unread = (friend.unread || 0) + 1;
                        console.log('[subscribeOfflineMessages] 更新后的未读计数:', friend.unread);
                    }
                } catch (error) {
                    console.error('[subscribeOfflineMessages] 解析离线消息失败:', error, '原始消息:', message.body);
                }
            });
        },

        subscribeStatusUpdates() {
            console.log('[subscribeStatusUpdates] 订阅状态更新频道');
            if (this.connectionStatus !== 'connected') return;

            this.stompClient.subscribe('/user/queue/status', (message) => {
                console.log('[subscribeStatusUpdates] 收到状态更新:', message);
                try {
                    const statusData = JSON.parse(message.body);
                    if (statusData.userId && statusData.status !== undefined) {
                        this.updateFriendStatus(statusData.userId, statusData.status);
                    }
                } catch (error) {
                    console.error('[subscribeStatusUpdates] 解析状态更新失败:', error);
                }
            });
        },

        unsubscribe() {
            console.log('[unsubscribe] 取消订阅所有频道');
            if (this.connectionStatus !== 'connected') return;
            this.stompClient.unsubscribe('/topic/messages');
            this.stompClient.unsubscribe('/user/queue/private');
            this.stompClient.unsubscribe('/user/queue/status');
            this.stompClient.unsubscribe('/user/queue/offline');
        },

        subscribe() {
            console.log('[subscribe] 订阅公共频道');
            if (this.connectionStatus !== 'connected') return;
            this.stompClient.subscribe('/topic/messages', (message) => {
                console.log('[subscribe] 收到公共频道消息:', message);
                try {
                    const rawMessage = message.body;
                    const messageId = message.headers['message-id'];
                    console.log('[subscribe] 消息ID:', messageId, '内容:', rawMessage, "最后发送的消息ID:", this.lastSentMessageId);

                    if (messageId === this.lastSentMessageId) {
                        console.log('[subscribe] 忽略自己发送的消息，ID:', messageId);
                        return;
                    }

                    const parts = rawMessage.split('|').map(s => s.trim());
                    if (parts.length < 2) {
                        console.error('[subscribe] 消息格式不正确:', rawMessage);
                        return;
                    }

                    const senderPart = parts[0];
                    const senderMatch = senderPart.match(/【(.*?)】/);
                    const sender = senderMatch ? senderMatch[1] : '未知发送方';

                    const jsonStart = senderPart.indexOf('{');
                    const jsonEnd = senderPart.lastIndexOf('}');
                    if (jsonStart === -1 || jsonEnd === -1) {
                        console.error('[subscribe] 找不到JSON内容:', senderPart);
                        return;
                    }

                    const jsonStr = senderPart.slice(jsonStart, jsonEnd + 1);
                    const contentObj = JSON.parse(jsonStr);
                    const content = contentObj.content;

                    const timeStr = parts[1];
                    const time = new Date(timeStr).toLocaleString();

                    const newMessage = {
                        sender,
                        content,
                        time,
                        isSelf: false,
                        messageId
                    };

                    console.log('[subscribe] 解析后的消息:', newMessage);
                    this.receivedMessages.push(newMessage);
                    console.log('[subscribe] 当前消息列表:', this.receivedMessages);
                } catch (error) {
                    console.error('[subscribe] 解析消息失败:', error, '原始消息:', message.body);
                }
            })
        },

        // 订阅私聊频道
        subscribePrivateChat() {
            console.log('[subscribePrivateChat] 订阅私聊频道');
            if (this.connectionStatus !== 'connected') return;
            this.stompClient.subscribe('/user/queue/private', (message) => {
                console.log('[subscribePrivateChat] 收到私聊消息:', message);
                try {
                    const messageData = JSON.parse(message.body);
                    console.log('[subscribePrivateChat] 解析后的私聊消息数据:', messageData);

                    const { from, content, timestamp, messageId } = messageData;
                    if (!messageData.from) {
                        console.error('[subscribePrivateChat] 错误：消息缺少 from', messageData);
                        return;
                    }

                    // 初始化该好友的消息数组
                    if (!this.privateMessages[from]) {
                        console.log('[subscribePrivateChat] 初始化好友消息数组，好友ID:', from);
                        this.privateMessages[from] = [];
                    }

                    const newPrivateMessage = {
                        from,
                        content,
                        timestamp: new Date(timestamp),
                        isSelf: false,
                        messageId
                    };

                    console.log('[subscribePrivateChat] 准备添加的私聊消息:', newPrivateMessage);
                    this.privateMessages[from].push(newPrivateMessage);
                    console.log('[subscribePrivateChat] 更新后的私聊消息列表:', this.privateMessages[from]);

                    // 更新好友未读消息计数
                    const friend = this.friendList.find(f => f.id === from);
                    if (friend) {
                        console.log('[subscribePrivateChat] 更新好友未读计数，好友ID:', from, '当前未读:', friend.unread || 0);
                        friend.unread = (friend.unread || 0) + 1;
                        console.log('[subscribePrivateChat] 更新后的未读计数:', friend.unread);
                    }
                } catch (error) {
                    console.error('[subscribePrivateChat] 解析私聊消息失败:', error, '原始消息:', message.body);
                }
            });
        },

        // 订阅群聊频道
        subscribeGroupChat(groupId) {
            console.log('[subscribeGroupChat] 订阅群聊频道，群组ID:', groupId);
            if (this.connectionStatus !== 'connected') return;
            this.stompClient.subscribe(`/group/group/${groupId}`, (message) => {
                console.log('[subscribeGroupChat] 收到群聊消息:', message.body);
            })
        },

        send(message) {
            console.log('[send] 发送公共消息:', message);
            if (this.connectionStatus !== 'connected') return;

            const messageId = `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
            this.lastSentMessageId = messageId;

            const newMessage = {
                sender: '你',
                content: message,
                time: new Date().toLocaleString(),
                isSelf: true,
                status: '发送中',
                messageId
            };

            console.log('[send] 添加到本地消息列表:', newMessage);
            this.receivedMessages.push(newMessage);

            const publishData = {
                destination: '/app/chat',
                body: JSON.stringify({
                    content: message
                }),
                headers: {
                    'message-id': messageId
                }
            };

            console.log('[send] 发布消息:', publishData);
            this.stompClient.publish(publishData);

            const lastMsgIndex = this.receivedMessages.length - 1;
            setTimeout(() => {
                console.log('[send] 更新消息状态为已发送，消息索引:', lastMsgIndex);
                this.receivedMessages[lastMsgIndex].status = '已发送';
            }, 1000);
        },

        // 发送私聊消息
        sendToUser(message, userId) {
            console.log('[sendToUser] 发送私聊消息给用户:', userId, '内容:', message);
            if (this.connectionStatus !== 'connected') return;

            const messageId = `private-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

            // 初始化该好友的消息数组
            if (!this.privateMessages[userId]) {
                console.log('[sendToUser] 初始化好友消息数组，好友ID:', userId);
                this.privateMessages[userId] = [];
            }

            const newPrivateMessage = {
                from: this.currentUser.id,
                content: message,
                timestamp: new Date(),
                isSelf: true,
                status: '发送中',
                messageId
            };

            console.log('[sendToUser] 添加到本地消息列表:', newPrivateMessage);
            this.privateMessages[userId].push(newPrivateMessage);

            const publishData = {
                destination: `/app/chat/user/${userId}`,
                body: JSON.stringify({
                    from: this.currentUser.id,
                    to: userId,
                    content: message,
                    timestamp: new Date().toISOString(),
                    messageId
                })
            };

            console.log('[sendToUser] 发布私聊消息:', publishData);
            this.stompClient.publish(publishData);

            // 更新消息状态
            const lastMsgIndex = this.privateMessages[userId].length - 1;
            setTimeout(() => {
                console.log('[sendToUser] 更新消息状态为已发送，消息索引:', lastMsgIndex);
                this.privateMessages[userId][lastMsgIndex].status = '已发送';
            }, 1000);
        },

        // 发送群聊消息
        sendToGroup(message, groupId) {
            console.log('[sendToGroup] 发送群聊消息到群组:', groupId, '内容:', message);
            if (this.connectionStatus !== 'connected') return;
            this.stompClient.publish({
                destination: `/app/chat/group/${groupId}`,
                body: JSON.stringify({
                    content: message
                })
            });
        },

        disconnect() {
            console.log('[disconnect] 断开WebSocket连接');
            if (this.connectionStatus !== 'connected') return;

            // 清除所有在线状态轮询
            Object.values(this.onlineStatusPolling).forEach(intervalId => {
                clearInterval(intervalId);
            });
            this.onlineStatusPolling = {};

            this.stompClient.deactivate();
            this.lastSentMessageId = null;
        },

        // 获取与指定好友的私聊消息
        getPrivateMessages(friendId) {
            console.log('[getPrivateMessages] 获取好友私聊消息，好友ID:', friendId, '消息:', this.privateMessages[friendId] || []);
            return this.privateMessages[friendId] || [];
        },

        // 清除好友的未读消息计数
        clearUnreadCount(friendId) {
            console.log('[clearUnreadCount] 清除好友未读计数，好友ID:', friendId);
            const friend = this.friendList.find(f => f.id === friendId);
            if (friend) {
                console.log('[clearUnreadCount] 清除前未读计数:', friend.unread);
                friend.unread = 0;
                console.log('[clearUnreadCount] 清除后未读计数:', friend.unread);
            }
        }
    },
    getters: {
        groupedFriendList: (state) => {
            return [
                state.friendGroups.online,
                state.friendGroups.offline
            ].filter(group => group.friends.length > 0);
        }
    }
})

// 辅助函数：格式化最后活跃时间
function formatLastSeen(timestamp) {
    if (!timestamp) return '未知';

    const now = new Date();
    const lastActive = new Date(timestamp);
    const diffInHours = (now - lastActive) / (1000 * 60 * 60);

    if (diffInHours < 1) {
        return `${Math.floor(diffInHours * 60)}分钟前`;
    } else if (diffInHours < 24) {
        return `${Math.floor(diffInHours)}小时前`;
    } else {
        return `${Math.floor(diffInHours / 24)}天前`;
    }
}

export const useChatSimpleStore = chatSimpleStore